package com.joker.utily;

//分离数据库配置

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DButil {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    //本地库
    static final String DB_URL = "jdbc:mysql://localhost:3306/book?useSSL=true&useUnicode=true&characterEncoding=utf8";
    //远程库
   // static final String DB_URL = "jdbc:mysql://47.117.0.64:3306/books?characterEncoding=utf-8&amp;useUnicode=true&amp;useSSL=true";
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "zhang123";

    static Connection conn = null;
    static Statement stmt = null;
    public DButil(){

    }

    public static void init() throws ClassNotFoundException, SQLException {
        Class.forName(JDBC_DRIVER);
        // 打开链接
        System.out.println("连接数据库...");
        conn = DriverManager.getConnection(DB_URL,USER,PASS);
    }
    //insert插入
    public static void add(String tablename,Object[] name,Object[] value) throws SQLException, ClassNotFoundException {
        init();
        String tname ="";
        String tvalue="";
       // String sql="insert into "+tablename+"("+tname+")";
        for (int i = 0; i <name.length ; i++) {
            if(i!=name.length-1){
                tname=tname+name[i]+",";
            }
            else {
                tname=tname+name[i];
            }
        }
        for (int i = 0; i <name.length ; i++) {
            if(i!=name.length-1){
                tvalue=tvalue+"?,";
            }
            else {
                tvalue=tvalue+"?";
            }
        }
        String sql="insert into "+tablename+"("+tname+")"+" value("+tvalue+")";
        System.out.println(sql);
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        for (int i = 0; i <value.length ; i++) {
            preparedStatement.setObject(i+1,value[i]);
        }
        preparedStatement.executeUpdate();
        preparedStatement.close();
        conn.close();

    }

    public static int update(){
        return 0;
    }
    public static int delete(){
        return 0;
    }
    public static List select(){
        List arrlist=new ArrayList();
        return arrlist;
    }

}
